package com.api.util;

import com.alibaba.fastjson.JSONObject;
import com.api.pojo.Rest;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

/**
 * 接口工具类
 */
public class RestUtil {
    public static List<Rest> rests = new ArrayList<Rest>();
    public static Map<String,String> authenticInfoMap = new HashMap<String, String>();
    public static String sign=PropertiesUtil.getSign();

    static {
        ExcelUtil.loadDatas(PropertiesUtil.getCaseFilePath(), "接口信息",Rest.class);
    }

    public static String process(String url, String type, String params){
        Map<String,String> paramsmap = (Map<String, String>) JSONObject.parse(params);
        String result ="";
        if("post".equalsIgnoreCase(type)){
            result = doPost(url,paramsmap);
        }else if("get".equalsIgnoreCase(type)){
            result = doGet(url);

        }else{
            System.out.print("请求方式暂时无法处理");
        }
        return result;
    }
private static String doPost(String url, Map<String,String> paramsmap){
    HttpPost httpPost = new HttpPost(url);
    String result="";
    List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
    try {
        Set<Map.Entry<String, String>> entries= paramsmap.entrySet();
        for(Map.Entry<String, String> entry:entries){
            NameValuePair pair = new BasicNameValuePair(entry.getKey().trim(),entry.getValue().trim());
            paramsList.add(pair);

        }

        //将参数封装在请求体中
        httpPost.setEntity(new UrlEncodedFormEntity(paramsList,"UTF-8"));
        //创建客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //添加认证鉴权信息
        addAuthenticInfo(httpPost);
        //发送接口请求,获取接口响应
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        //取出鉴权的头信息，并且保存
        saveAuthenticInfo(httpResponse);
        //获取响应数据，为json格式，转换为字符串
        HttpEntity resultJson = httpResponse.getEntity();
        //将json转换为字符串
        System.out.println(resultJson);
        //result = String.valueOf(resultJson);
        result = EntityUtils.toString(resultJson);
        JSONObject jsonObject=JSONObject.parseObject(result);
        System.out.println(jsonObject.toJSONString());
        //System.out.println(result);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

    private static void saveAuthenticInfo(CloseableHttpResponse httpResponse) {
        Header header = httpResponse.getFirstHeader("set-Cookie");
        if(header!=null){
          String value =   header.getValue();
          int index=value.indexOf("JSESSIONID");
          if(value!=null&&index!=-1){
              String authenticInfo = value.substring(index,value.indexOf(";"));
              authenticInfoMap.put("jsessionId",authenticInfo);


          }

        }
    }

    /**添加鉴权信息
     * @param
     */
    private static void addAuthenticInfo(HttpRequest httpRequest) {
           String value=authenticInfoMap.get("jsessionId");
           if(value!=null&&value.trim().length()>0){
               httpRequest.addHeader("Cookie",value);


           }

    }


    private static String doGet(String url){
        //Set<Map.Entry<String,String>> entries = paramsmap.entrySet();
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        //String processed="";
        String result="";
        /*
        for(Map.Entry<String,String> entry:entries){
            NameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue());
            paramList.add(pair);
            //url+=("?"+entry.getKey()+"="+entry.getValue());
            //processed+=("&"+entry.getKey()+"="+entry.getValue());

        }
        */
        String formatedURL = URLEncodedUtils.format(paramList,"UTF-8");
        //url+=("?"+formatedURL);
    HttpGet httpGet = new HttpGet(url);
    //准备接口地址
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
         addAuthenticInfo(httpGet);
        //发送接口请求,获取接口响应
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        saveAuthenticInfo(httpResponse);
        //获取响应数据，为json格式，转换为字符串
        HttpEntity resultJson = httpResponse.getEntity();
        //将json转换为字符串
        System.out.println(resultJson);
        result = EntityUtils.toString(resultJson);
        JSONObject jsonObject=JSONObject.parseObject(result);
        System.out.println(jsonObject.toJSONString());
        //System.out.println(result);


    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}





        public static void main(String[] args){
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobilephone","13517315120"));
            paramList.add(new BasicNameValuePair("amount","12345"));
            String formatedURL = URLEncodedUtils.format(paramList,"UTF-8");
            System.out.println(formatedURL);
            }


    /**
     * @param apiId  根据接口id获取url地址
     * @return
     */
    public static String getUrlByApiId(String apiId) {
    //一次获取所有数据（在静态代码块中实现），再进行筛选
        for(Rest rest:rests){
            if(rest.getApiId().equals(apiId)){
                return rest.getUrl()+sign;

            }

        }
        return null;
    }

    /**根据id获取接口的类型
     * @param apiId
     * @return
     */
    public static String getTypeByApiId(String apiId) {
        for(Rest rest:rests){
            if(rest.getApiId().equals(apiId)){
                return  rest.getType();

            }

        }
        return null;
    }

}
    
    


